package com.turman.common.tab

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.annotation.NonNull
import androidx.fragment.app.Fragment

class FragmentTabView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    private var mAdapter: TabViewAdapter? = null
    private var currentPosition: Int = -1

    fun getAdapter(): TabViewAdapter? = mAdapter
    fun setAdapter(@NonNull adapter: TabViewAdapter) {
        if (mAdapter != null) {
            return
        }
        mAdapter = adapter
        currentPosition = -1
    }

    fun setCurrentItem(position: Int) {
        if (position < 0 || position >= mAdapter?.getCount() ?: 0) {
            return
        }

        if (currentPosition != position) {
            currentPosition = position
            mAdapter?.instantiateItem(this, position)
        }
    }

    /**
     * 获取当前展示页索引
     * @author buobao
     * @since 2024/3/12 10:39
     */
    fun getCurrentItem(): Int {
        return currentPosition
    }

    /**
     * 获取当亲fragment
     * @author buobao
     * @since 2024/3/12 10:39
     */
    fun getCurrentFragment(): Fragment? {
        if (mAdapter == null) {
            throw IllegalArgumentException("place set adapter first")
        } else {
            return mAdapter?.mCurrentFragment
        }
    }
}